import { getServerMap, getPositionList } from '@/api/common'
import { getDepartmentList } from '@/api/department'

const getDefaultState = () => {
  return {
    // 服务器列表
    serverMap: null,
    // 服务器列表最后一次刷新时间
    servermapLastRefreshTime: -1,
    // 部门列表
    departmentList: null,
    // 部门列表最后一次刷新时间
    departmentListLastRefreshTime: -1,
    // 岗位列表
    positionList: null,
    // 岗位列表最后一次刷新时间
    positionListLastRefreshTime: -1
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_SERVER_MAP: (state, serverMap) => {
    state.serverMap = serverMap
  },
  SET_SERVERMAP_REFRESH_TIME: (state, refreshTime) => {
    state.servermapLastRefreshTime = refreshTime
  },
  SET_DEPARTMENT_LIST: (state, departmentList) => {
    state.departmentList = departmentList
  },
  SET_DEPARTMENT_REFRESH_TIME: (state, refreshTime) => {
    state.departmentListLastRefreshTime = refreshTime
  }
}

const actions = {
  serverMap({ commit, state }, force = false) {
    console.log('getServerMap', state.servermapLastRefreshTime, force)
    if (!force && state.serverMap && Date.now() - state.servermapLastRefreshTime < 1000 * 60 * 10) { // 10分钟之内用缓存的
      return state.serverMap
    }
    return new Promise((resolve, reject) => {
      getServerMap({ force }).then(data => {
        const { serverMap } = data
        commit('SET_SERVER_MAP', serverMap)
        commit('SET_SERVERMAP_REFRESH_TIME', Date.now())
        resolve(serverMap)
      }).catch(error => {
        reject(error)
      })
    })
  },
  departmentList({ commit, state }, force = false) {
    if (!force && state.departmentList && Date.now() - state.departmentListLastRefreshTime < 1000 * 60 * 10) { // 10分钟之内用缓存的
      return state.departmentList
    }
    return new Promise((resolve, reject) => {
      getDepartmentList({ force }).then(data => {
        const { list } = data
        commit('SET_DEPARTMENT_LIST', list)
        commit('SET_DEPARTMENT_REFRESH_TIME', Date.now())
        resolve(list)
      }).catch(error => {
        reject(error)
      })
    })
  },
  positionList({ commit, state }, force = false) {
    if (!force && state.positionList && Date.now() - state.positionListLastRefreshTime < 1000 * 60 * 10) { // 10分钟之内用缓存的
      return state.positionList
    }
    return new Promise((resolve, reject) => {
      getPositionList({ force }).then(data => {
        const { list } = data
        commit('SET_POSITION_LIST', list)
        commit('SET_POSITIONLIST_REFRESH_TIME', Date.now())
        resolve(list)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

